/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */
package com.yami.shop.distribution.platform.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.EnterprisePayStatus;
import com.yami.shop.common.config.Constant;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.distribution.common.constants.DistributionAudit;
import com.yami.shop.distribution.common.model.DistributionUser;
import com.yami.shop.distribution.common.model.DistributionUserWallet;
import com.yami.shop.distribution.common.model.DistributionWithdrawCash;
import com.yami.shop.distribution.common.param.RangeTimeParam;
import com.yami.shop.distribution.common.service.DistributionUserService;
import com.yami.shop.distribution.common.service.DistributionUserWalletService;
import com.yami.shop.distribution.common.service.DistributionWithdrawCashService;
import com.yami.shop.distribution.common.vo.DistributionConfigVO;
import com.yami.shop.security.common.enums.SocialType;
import com.yami.shop.security.common.model.AppConnect;
import com.yami.shop.security.common.service.AppConnectService;
import com.yami.shop.service.SysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Objects;

/**
 * @author lgh on 2019/04/01.
 */
@RestController
@RequestMapping("/platform/distributionWithdrawCash")
@Api(tags = "平台端分销员提现申请接口")
public class DistributionWithdrawCashController {

    @Autowired
    private DistributionWithdrawCashService distributionWithdrawCashService;
    @Autowired
    private DistributionUserWalletService distributionUserWalletService;
    @Autowired
    private DistributionUserService distributionUserService;
    @Autowired
    private AppConnectService appConnectService;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 分页获取
     */
    @GetMapping("/page")
    @PreAuthorize("@pms.hasPermission('platform:distributionWithdrawCash:page')")
    @ApiOperation(value = "分页获取分销员提现申请列表")
    @ApiImplicitParam(name = "userMobile", value = "分销员手机号码", dataType = "String")
    public ServerResponseEntity<IPage<DistributionWithdrawCash>> page(PageParam<DistributionWithdrawCash> page, RangeTimeParam rangeTimeParam,
                                                                String userMobile, DistributionWithdrawCash distributionWithdrawCash) {
        IPage<DistributionWithdrawCash> list = distributionWithdrawCashService.distributionWithdrawCashsPage(page, null, rangeTimeParam, userMobile, distributionWithdrawCash);
        return ServerResponseEntity.success(list);
    }

    /**
     * 修改
     */
    @PutMapping("/toSuccess/{withdrawCashId}")
    @PreAuthorize("@pms.hasPermission('platform:distributionWithdrawCash:update')")
    @ApiOperation(value = "修改分销员提现申请信息")
    @ApiImplicitParam(name = "withdrawCashId", value = "提现记录id", dataType = "String")
    public ServerResponseEntity<Void> update(@PathVariable String withdrawCashId) {
        DistributionWithdrawCash distributionWithdrawCash = distributionWithdrawCashService.getById(withdrawCashId);
        if (distributionWithdrawCash == null) {
            throw new YamiShopBindException("yami.get.user.cash.info");
        }
        Long walletId = distributionWithdrawCash.getWalletId();
        DistributionUserWallet wallet = distributionUserWalletService.getById(walletId);
        if (wallet == null) {
            throw new YamiShopBindException("yami.get.user.withdraw.info");
        }
        DistributionUser distributionUser = distributionUserService.getById(wallet.getDistributionUserId());
        if (distributionUser == null) {
            throw new YamiShopBindException("yami.user.no.exist");
        }
        if (!Objects.equals(distributionUser.getShopId(), Constant.PLATFORM_SHOP_ID)) {
            throw new YamiShopBindException("yami.withdrawCash.update.no.auth");
        }
        distributionWithdrawCash.setState(1);
        distributionWithdrawCash.setUpdateTime(new Date());
        distributionWithdrawCashService.updateById(distributionWithdrawCash);

        // 判断打款状态 1审核通过企业打款 2审核通过人工打款
        //获取店铺提现设置
        DistributionConfigVO distributionConfigVO = sysConfigService.getSysConfigObject(Constant.DISTRIBUTION_CONFIG, DistributionConfigVO.class);
        if (!distributionConfigVO.getWithdrawal().equals(DistributionAudit.Withdrawals_ONE.getValue())){
            return ServerResponseEntity.success();
        }
        // 获取用户的openId
        DistributionUserWallet one = distributionUserWalletService.getOne(new LambdaQueryWrapper<DistributionUserWallet>().eq(DistributionUserWallet::getWalletId, distributionWithdrawCash.getWalletId()));
        AppConnect appConnect = appConnectService.getOne(new LambdaQueryWrapper<AppConnect>()
                .eq(AppConnect::getUserId, distributionUserService.getById(one.getDistributionUserId()).getUserId())
                .eq(AppConnect::getAppId, SocialType.MA.value())
        );
        // 添加企业支付记录
        distributionWithdrawCashService.enterprisePay(distributionWithdrawCash, appConnect.getUserId(), appConnect.getBizUserId(), EnterprisePayStatus.APPLY.getValue());

        return ServerResponseEntity.success();
    }
}
